<?php

/**
 * 說明 : 顯示jsonp格式
 * 
 * 使用方法 : 
 *
 *          use FS\Library\JsonP;
 *          JsonP::show($results);
 *
 */

namespace FS\Library;

class JsonP { 

	public function show( $data ){ 

        header('content-type: application/json; charset=utf-8');

        // 參考
        // 利用JSONP/ CORS實現Cross-Origin Request   http://ericachang.github.io/2013/07/01/jsonp_and_cors/
        if ($_SERVER['REQUEST_METHOD'] == "OPTIONS") {

            // Tell the Client we support invocations and that this preflight holds good for only 20 days
            header('Access-Control-Allow-Origin: *');
            header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
            header('Access-Control-Max-Age: 1728000');
            header("Content-Length: 0");
            header("Content-Type: application/json");

        } elseif($_SERVER['REQUEST_METHOD'] == "GET" || "POST") {

            header('Access-Control-Allow-Origin: *');
            header('Content-Type: application/json');

        } else {

            die("No Other Methods Allowed");
        }


        // 如果是jsonp方式
        // jquery 會將ajax success的function自動命名,並將function名稱放在 $_GET['callback']
        // 所以這裡顯示執行呼叫端的function
        echo $_GET['callback']  . '('.json_encode($data).')';

    }
}


